#include <iostream>
#include <string>
#include <memory>

class Fruit
{
public:
    virtual void name() = 0;
};

class Apple : public Fruit
{
public:
    void name() override
    {
        std::cout << "这是一个苹果" << std::endl;
    }
};

class Pear : public Fruit
{
public:
    void name() override
    {
        std::cout << "这是一个梨" << std::endl;
    }
};

// 工厂方法模式:每一个产品有其专有的工厂
// 优点: 遵循开闭原则
// 缺点: 如果有大量的产品, 需要创建大量的工厂类, 代码量大
class FruitFactory
{
public:
    virtual std::shared_ptr<Fruit> create() = 0;
};

class AppleFactory : public FruitFactory
{
public:
    std::shared_ptr<Fruit> create() override
    {
        return std::make_shared<Apple>();
    };
};

class PearFactory : public FruitFactory
{
public:
    std::shared_ptr<Fruit> create() override
    {
        return std::make_shared<Pear>();
    };
};

int main()
{
    std::shared_ptr<FruitFactory> factory (new AppleFactory());
    std::shared_ptr<Fruit> fruit = factory->create();
    fruit->name();
    factory.reset(new PearFactory());
    fruit=factory->create();
    fruit->name();
    return 0;
}